<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\Dept;
use common\services\PermissionService;
use common\services\system\DeptService;
use Yii;
use yii\db\ActiveQuery;
use yii\db\Expression;

class DeptController extends AuthController
{
    use CommonAction;

    protected string $model = Dept::class;
    protected bool $validate = true;
    protected array $noAction = ['status'];


    protected function listQuery(ActiveQuery $query): ActiveQuery
    {
        $rootDeptId = Yii::$app->params['root_dept_id'];
        $where = [];
        // 当不是超级管理员时，指定权限内的部门
        if (!PermissionService::isAdmin($this->user_id)) {
            $userDeptList = DeptService::selectDeptByUserId($this->user_id);
            if (!$userDeptList) return $query->andWhere(['id'=>0]);
            $userValidDeptId = [];

            foreach ($userDeptList as $dept) {
                if ($dept['id'] == $rootDeptId) return $query;
                $userValidDeptId[] = $dept['id'];
            }

            if (!$userValidDeptId) return $query->andWhere(['id'=>0]);
            $where[] = 'or';
            foreach ($userValidDeptId as $userDeptId) {
                $where[] = ['id' => $userDeptId];
                $where[] = new Expression('FIND_IN_SET("' . $userDeptId . '", levels)');
            }
        }
        return $where ? $query->andWhere($where) : $query;
    }

    /**
     * 获取列表，用于添加编辑的级联选择
     * @return array
     */
    public function actionGetSelect(): array
    {
        return $this->success('', ['list' => DeptService::selectDeptUserSelectList($this->user_id)]);
    }

    /**
     * 指定排序
     * @param array $params
     * @return array
     */
    protected function listBefore(array $params): array
    {
        $params['orderBy'] = ['parent_id' => 'asc', 'list_sort' => 'asc'];
        return $params;
    }

    /**
     * 保存前判断处理
     * @param Dept $model
     * @param string $type
     * @return string
     */
    protected function saveBefore(Dept $model, string $type): string
    {
        if ($type == 'add' || $type == 'edit') {
            $root_id = intval($this->app->params['root_dept_id']);
            if ($type == 'add' && !$model->parent_id) return '请选择上级部门';
            if ($type == 'edit') {
                if ($model->id == $root_id && $model->parent_id) return '顶级部门不能修改上级部门';
                if ($model->id == $model->parent_id) return '上级部门不能是自己';
            }
            if ($model->parent_id) {
                $parentInfo = Dept::findOne($model->parent_id);
                if (!$parentInfo) return '上级部门信息不存在';
                $levels = explode(',', $parentInfo->levels);
                if (in_array($model->id, $levels)) return '上级部门不能是自己的子部门';
                $model->parent_name = trim($parentInfo->parent_name . ',' . $parentInfo->name, ',');
                $model->levels = trim($parentInfo->levels . ',' . $parentInfo->id, ',');
            }
        }
        return '';
    }

    /**
     * 保存后更新子级的parent_name和levels
     * @param Dept $model
     * @param string $type
     */
    protected function saveAfter(Dept $model, string $type): void
    {
        if ($type == 'edit') DeptService::updateChildExtendField($model->id);
    }

    /**
     * 删除前判断
     * @param Dept $model
     * @param string $type
     * @return string
     */
    protected function deleteBefore(Dept $model, string $type): string
    {
        if ($model->id == $this->app->params['root_dept_id']) return '根组织部门无法删除';
        $child = Dept::findOne(['parent_id' => $model->id]);
        if ($child) return '该组织下有子组织，无法删除';
        return '';
    }

}
